package com.lenovo.nova.util;

import java.io.*;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.*;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.*;

import com.lenovo.nova.util.debug.mylog;
import com.lenovo.nova.util.debug.slog;
import com.lenovo.nova.util.exec.JavaShellUtil;
import com.lenovo.nova.util.network.NetworkUtils;
import com.lenovo.nova.util.view.KeyUtil;
import com.lenovo.nova.widget.dialog.BaseDialogFragment;
import com.lenovo.nova.widget.windowmanager.WindowManagerArrow;

@SuppressLint("ValidFragment")
public class BaseActivity extends Activity {
    private JavaShellUtil mLogcatExecute;

    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mylog.i(Constant.Debug.METHOD_TAG,getName() + "onCreate");
		sContext.set(this);
		Applications.get(this).init();
		Applications.get(this).setActivityAlive(true);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mylog.i(Constant.Debug.METHOD_TAG,getName() + "onDestroy");
		Applications.get(this).setActivityAlive(false);
	}

	@Override
	protected void onResume() {
		super.onResume();
		mylog.i(Constant.Debug.METHOD_TAG,getName() + "onResume");
		sContext.set(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		mylog.i(Constant.Debug.METHOD_TAG,getName() + "onPause");
	}

	@Override
	protected void onStart() {
		super.onStart();
		mylog.i(Constant.Debug.METHOD_TAG,getName() + "onStart");
	}

	@Override
	protected void onStop() {
		super.onStop();
		mylog.i(Constant.Debug.METHOD_TAG,getName() + "onStop");
	}

	@Override
	protected void onApplyThemeResource(Resources.Theme theme, int resid, boolean first) {
		super.onApplyThemeResource(theme, resid, first);
		mylog.i(Constant.Debug.METHOD_TAG,getName() + "onApplyThemeResource " + theme + " resid " + resid + " first " + first);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		mylog.i(Constant.Debug.METHOD_TAG,getName() + "onNewIntent " + intent);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mylog.i(Constant.Debug.METHOD_TAG,getName() + "onRestoreInstanceState " );
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mylog.i(Constant.Debug.METHOD_TAG,getName() + "onSaveInstanceState " );
	}

	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		mylog.i(Constant.Debug.METHOD_TAG,getName() + "onAttachedToWindow " );
	}

	@Override
	public void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		mylog.i(Constant.Debug.METHOD_TAG,getName() + "onDetachedFromWindow " );
	}

	@SuppressLint("NewApi")
	@Override
	public boolean onGenericMotionEvent(MotionEvent event) {
		if(Applications.isInDebugMode){
			mylog.d(Constant.Debug.METHOD_TAG,getName() + "onGenericMotionEvent " + event);
		}
		return super.onGenericMotionEvent(event);
	}

	@SuppressLint("NewApi")
	@Override
	public boolean dispatchGenericMotionEvent(MotionEvent ev) {
        mylog.d(Constant.Debug.METHOD_TAG,getName() + "dispatchGenericMotionEvent " + ev);

		if (ev.getAction() == MotionEvent.ACTION_HOVER_MOVE || ev.getAction() == MotionEvent.ACTION_HOVER_ENTER || ev.getAction() == MotionEvent.ACTION_HOVER_EXIT) {
			inputModeChangeTouchMode(this);
		}
		
		Applications.get(this).notifyMotionEventChangeListener(ev);
		return super.dispatchGenericMotionEvent(ev);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
        if(Applications.isInDebugMode){
            mylog.d(Constant.Debug.METHOD_TAG,getName() + "dispatchTouchEvent " + ev);
        }
		inputModeChangeTouchMode(this);
        Applications.get(this).notifyTouchEventChangeListener(ev);
		return super.dispatchTouchEvent(ev);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		mylog.d(Constant.Debug.METHOD_TAG,getName() + "dispatchKeyEvent " + event);
		inputModeChangeToKeyBoard(this,event.getKeyCode());
		
		if(KeyUtil.isTouchBoardKey(event.getKeyCode())){
			Applications.get().notifyTouchBoardTouched(event);
		}
		
		return super.dispatchKeyEvent(event);
	}

    @Override
    public void finish() {
        Applications.get(this).setActivityAlive(false);
        for(WindowManagerArrow arrow : WindowManagerArrow.mAllInstance){
            arrow.close();
        }
        WindowManagerArrow.mAllInstance.clear();

        for (int i = 0; i < BaseDialogFragment.getAllInstance().size(); i++){
            BaseDialogFragment.getAllInstance().get(i).dismiss();
        }
        BaseDialogFragment.getAllInstance().clear();

        super.finish();
        mylog.i("BaseActivity","finish",2);
    }

    @Override
    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
        // 子类继承DebugUtil 重写dump时候方便直接使用
        DebugUtil.allInputCmd = args;
        DebugUtil.getInstance(this).dump(prefix, fd, writer, args);
    }



    /////////////////////////////////////////////////////

    public JavaShellUtil getLogcatExecute(){
        return mLogcatExecute;
    }

    public static void inputModeChangeTouchMode(Context context) {
		if (!Applications.get(context).isInTouchMode()) {
			Applications.get(context).notifyInputModeChange(true);
			Applications.get(context).setTouchMode(true);
			slog.p("input mode change to Touch");
		}
	}

	public static void inputModeChangeToKeyBoard(Context context,int keyCode) {
		if (Applications.get(context).isInTouchMode()) {
			if (KeyUtil.isDirectionKey(keyCode)) {
				// 除了方向按键，我们认为都是输入TouchMode
				Applications.get(context).setTouchMode(false);
				Applications.get(context).notifyInputModeChange(false);
				slog.p("input mode change to keyBroad");
			}
		}
	}


	protected void requestLandscape() {
		if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		}
	}


    protected String openLogcat(File logPath) {
        try {
            FileOutputStream outputStream = new FileOutputStream(logPath, false);
            mLogcatExecute = new JavaShellUtil();
            mLogcatExecute.executeLocalCmd("logcat -v time *:I", false, outputStream);
            return logPath.getAbsolutePath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void closeLogcat(){
        if(mLogcatExecute != null){
            mLogcatExecute.release();
        }
    }

	@SuppressLint("NewApi")
	protected void showAlertDialog(String msg){
		Builder dialog = new AlertDialog.Builder(this);
		dialog.setMessage(msg)
		.setTitle("错误提示")
		.setNegativeButton("确定", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		})
		.show();
	}
	
	protected void requestFullScreen(){
		//去掉标题栏
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		//去掉信息栏
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}

    protected void registerMonitorNetworkState(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mBroadReceiver,filter);
    }

    protected void unRegisterMonitorNetworkState(){
        unregisterReceiver(mBroadReceiver);
    }

    protected void onNetworkChange(boolean connected){

    }
    protected BroadcastReceiver mBroadReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            if(NetworkUtils.isNetworkConnected(BaseActivity.this)){
                onNetworkChange(true);
            }else{
                onNetworkChange(false);
            }
        }
    };

    public String getName() {
        return this.getClass().getSimpleName() + "-" + this.hashCode()+" ";
    }

}
